import { inject, observer } from 'mobx-react'
import React, { Component } from 'react'

@inject('mainStore')
@observer
export default class TodoHeader extends Component {
  state = {
    name: '',
  }
  // 实例方法
  handleKeyUp = (e) => {
    if (e.key === 'Enter') {
      const name = this.state.name
      if (name.trim() === '') return alert('不能为空')
      const { addTodo } = this.props.mainStore
      addTodo(name)
      this.setState({ name: '' })
    }
  }
  /* // 原型方法
  handleKeyUp() {}
  // 静态方法
  static handleKeyUp() {} */
  render() {
    const { name } = this.state
    return (
      <header className='header'>
        <h1>todos</h1>
        <input className='new-todo' placeholder='What needs to be done?' autoFocus value={name} onChange={(e) => this.setState({ name: e.target.value })} onKeyUp={this.handleKeyUp} />
      </header>
    )
  }
}
